<?php
namespace app\common\controller;
use think\Controller;
use think\facade\Cache;
use lib\wechat\WechatAppPay;
use base\pay\WxApi;
use base\pay\AliPayApi;
use app\common\model\Order as OrderModel;
use app\common\model\UserRecharge;
use app\common\model\ShopRecharge;


class PayNotify extends Controller 
{
	
	/**
	* 微信H5支付成功通知
	* wx/wxPayNotice
	* 不需要登录 
	* @is_need_login false
	*/
    public function wxPayNotice()
    {
        $config = env('system_base_config_wx_web'); 
    	$postStr = !empty($this->postxml) ? $this->postxml:file_get_contents("php://input");
    	$param = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
		if( 
			$param['return_code'] =="SUCCESS" && 
			$param["mch_id"] = $config['mch_id']
		){
			$openid = $param['openid'];
			$orderNo  = $param['out_trade_no'];
			$transaction_id = $param['transaction_id'];
			
			//店铺充值
			if( strstr($orderNo,"dcz") ){
				return ShopRecharge::paySuccess($orderNo,$transaction_id);
			}
			
			//会员充值
			if( strstr($orderNo,"cz") ){
				return UserRecharge::paySuccess($orderNo,$transaction_id);
			}
			
			//订单
			if( !(new OrderModel)->paySuccess($orderNo,'wx',$transaction_id) ){
				return fasle;
			}
			
		}

		$data['return_code'] = 'SUCCESS';
		$data['return_msg'] = 'OK';
		$xml = wechatAppPay::data_to_xml($data);
		echo $xml;
		die();
    }
	
	
	/**
    * 支付宝支付异步通知
	*alipay/aliPayNotify 
	* @is_need_login false
    */
    public function aliPayNotify()
    {
        $request    = input('post.');
        $signType = $request['sign_type'];
        $alipay = new AliPayApi();
        $flag = $alipay->rsaCheck($request, $signType);
        if ($flag) {
            //支付成功:TRADE_SUCCESS   交易完成：TRADE_FINISHED
            if ($request['trade_status'] == 'TRADE_SUCCESS' || $request['trade_status'] == 'TRADE_FINISHED') {
                //这里根据项目需求来写你的操作 如更新订单状态等信息 更新成功返回'success'即可
                $out_trade_no   =   $request['out_trade_no'];
				if( (new OrderModel)->paySuccess($out_trade_no,'alipay') ){
					exit('fail');
				}else{
					exit('success'); //成功处理后必须输出这个字符串给支付宝
				}
            } else {
                exit('fail');
            }
        } else {
            exit('fail');
        }
    }

	/**
	* 获取支付宝支付信息
	* common/pay/AliPayInfo
	* 不需要登录 
	* @is_need_login false
	*/
    public function getAliPayInfo($order_no)
    {
    	echo  Cache('AliPayApi_orderNo_'.$order_no);
		die();
    }
	
}



